/*
 * @Author: fah 1742484532@qq.com
 * @Date: 2024-09-13 16:44:35
 * @LastEditors: fah 1742484532@qq.com
 * @LastEditTime: 2024-09-14 16:14:29
 * @FilePath: \livetree-admin-server\src\auth\auth.service.ts
 * @Description: 指飞部-企业数字化管理系统
 * @version: 1.0
 */
import { HttpService } from '@nestjs/axios';
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { lastValueFrom } from 'rxjs';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import { responseMessage } from 'src/utils';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
    private httpService: HttpService,
  ) {}

  private sessionKeyInfo;
  public apiServer = 'https://api.weixin.qq.com';

  async signIn(username, pass) {
    // const user = await this.usersService.findOne(username);

    const payload = { sub: '1', username: '2' };
    const token = await this.jwtService.signAsync(payload);

    return responseMessage(token);
  }

  async signInByWechat(code, user_info) {
    console.log("signInByWechat", user_info)

    if (!code) {
      throw new BadRequestException('请输入微信授权码');
    }

    await this.getSessionKey(code)

    const user = await this.getUserByOpenid();

    if (!user) {
      // 获取用户信息，注册新用户
      const newUser = await this.usersService.registerByWechat({
        ...user_info,
        open_id: this.sessionKeyInfo.openid,
      });
      console.log('asa', newUser);
      return this.login(newUser);
    }

    const payload = { sub: '1', username: '2' };
    const token = await this.jwtService.signAsync(payload);
    
    return responseMessage(token)
  }

  async login(user) {

    const payload = { sub: '1', username: '2' };
    const token = await this.jwtService.signAsync(payload);
    
    return responseMessage(token);
  }
  async getSessionKey(code) {
    console.log("getSessionKey", process.env)
    const { APPID, APPSECRET } = process.env;
    if (!APPSECRET) {
      throw new BadRequestException('[getAccessToken]必须有appSecret');
    }
    if (
      !this.sessionKeyInfo ||
      (this.sessionKeyInfo && this.isExpires(this.sessionKeyInfo))
    ) {
      console.log('getAccessToken code', code);
      console.log('getAccessToken APPID', APPID);
      console.log('getAccessToken APPSECRET', APPSECRET);
      // 请求accessToken数据
      const res = await lastValueFrom(
        this.httpService.get(
          `${this.apiServer}/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${code}&grant_type=authorization_code`,
        ),
      );

      console.log('getAccessToken res', res.data);
      // if (res.data.errcode) {
      //   throw new BadRequestException(
      //     `[getAccessToken] errcode:${res.data.errcode}, errmsg:${res.data.errmsg}`,
      //   );
      // }
      this.sessionKeyInfo = {
        sessionKey: res.data.session_key,
        expiresIn: res.data.expires_in,
        getTime: Date.now(),
        openid: res.data.openid,
      };
    }

    return this.sessionKeyInfo.sessionKey;
  }

  async getUserByOpenid() {
    return await this.usersService.findByOpenid(this.sessionKeyInfo.openid);
  }

  isExpires(access) {
    return Date.now() - access.getTime > access.expiresIn * 1000;
  }
}
